package org.dant.ant.extension.tasks;

import java.io.*;
import java.util.*;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.TaskContainer;

import org.dant.ant.extension.tasks.internal.RemoteResponse;
import org.dant.ant.extension.xml.XMLResultFormatter;

public class TestSuite extends Task implements TaskContainer {
  protected String name = null;

  protected List nestedTasks = new LinkedList();
  
  protected boolean printSummary = false;

  protected File resultdir = null;

  private XMLResultFormatter formatter = new XMLResultFormatter();

  protected boolean isSuccess = true;

  public void setResultdir(File dir) {
    this.resultdir = dir;
  }

  public File getResultdir() {
    if (resultdir == null) return getProject().getBaseDir();
    return this.resultdir;
  }
  
  public String getName() {
    if (this.name == null) return "default test sutie";
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void setPrintsummary(boolean printSummary) {
    this.printSummary = printSummary;
  }

  public boolean getPrintsummary() {
    return this.printSummary;
  }


  public boolean isSuccess() {
    return this.isSuccess;
  }
  
  public void addTask(Task nestedTask) {
    nestedTasks.add(nestedTask);
  }

  protected void exportResult(RemoteResponse results) {
    formatter.writeResults(results, getResultdir());    
  }

  public void execute() throws BuildException {
    System.out.println("Running TestSuite: " + this.name);

    for (Iterator iter=nestedTasks.iterator();iter.hasNext();) {
      Task task = (Task) iter.next();
      if (task instanceof TestCase) {
        TestCase testcase = (TestCase) task;
        testcase.setOwningTestSuite(this);
        if (!testcase.isSuccess()) this.isSuccess = false;
        testcase.perform();
        exportResult(new RemoteResponse(testcase.getName(), this.name, RemoteResponse.TESTCASE, testcase.isSuccess()));
      } else {
        task.perform();
      }
    }
  }
}
